package com.interview.javabase.algorithm.hand;

import java.util.concurrent.atomic.AtomicReference;

public class 手写自旋锁 {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println("请求加锁" + thread.getName());
        while (!atomicReference.compareAndSet(null, thread)) {
            // 自旋
            System.out.println("自旋" + thread.getName());
        }
    }

    public void unLock() {
        Thread thread = Thread.currentThread();
        System.out.println("请求解锁" + thread.getName());
        atomicReference.compareAndSet(thread, null);
    }

    public static void main(String[] args) throws InterruptedException {
        手写自旋锁 d = new 手写自旋锁();
        new Thread(() -> {
            d.lock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            d.unLock();
        }, "AA").start();

        Thread.sleep(1000);

        new Thread(() -> {
            d.lock();
            d.unLock();
        }, "BB").start();
    }
}
